package com.jackiechancinema.ssm.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter("/*")
public class AuthFilter implements Filter {
    private String[] whiteUrls=new String[]{"/","login.html","/main/login.html","/main/login",".css",".js",".png",".jpg","jpeg","gif"};
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //1.验证是否登陆
        HttpServletRequest req=(HttpServletRequest) request;
        String rurl=req.getRequestURI().toString();
        if(req.getSession().getAttribute("curruser")==null){
            //未登录,检查是否是允许页面的接口：登陆页、登陆接口

            if(checkUrl(rurl)){
                //放行
                chain.doFilter(request,response);
            }else {
                //拦截
                HttpServletResponse resp= (HttpServletResponse) response;
                resp.sendRedirect("/");
            }
        }else {
            //放行
            chain.doFilter(request,response);
        }
    }
    private boolean checkUrl(String url){
        for(String s:whiteUrls){
            if(url.endsWith(s)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
